package com.ruoyi.web.controller.teaching;


import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.teaching.domain.VettingRequest;
import com.ruoyi.teaching.domain.vo.PlatformUResourceVO;
import com.ruoyi.teaching.service.PlatformUResourceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import java.net.URL;
import java.net.HttpURLConnection;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 王旭
 * @since 2024-06-26
 */
@RestController
@RequestMapping("/platform/resource")
@Api(tags = "platform-资源上传管理")
@Validated
public class PlatformUResourceController {
    @Autowired
    private PlatformUResourceService platformUResourceService;

    /**
     * 查询自己的资源上传列表
     */
//    @PreAuthorize("@ss.hasPermi('platform:resource:listOwn')")
    @GetMapping("/listOwn")
    @ApiOperation(value = "查询自己的资源上传列表", notes = "查询自己的资源上传列表")
    public AjaxResult listOwn(Integer pageNum,Integer pageSize,Integer resourceType,Integer vettingStatus,String resourceName)
    {
        return platformUResourceService.selectPlatformUResourceListOwn(pageNum, pageSize, resourceType, vettingStatus, resourceName);
    }

    /**
     * 后台系统管理员查询资源上传列表
     */
//    @PreAuthorize("@ss.hasPermi('platform:resource:listOwn')")
    @GetMapping("/listSystemAdmin")
    @ApiOperation(value = "后台系统管理员查询资源上传列表", notes = "后台系统管理员查询资源上传列表")
    public AjaxResult listSystemAdmin(Integer pageNum,Integer pageSize,Integer resourceType,Integer vettingStatus,String resourceName)
    {
        return platformUResourceService.selectPlatformUResourceListSystemAdmin(pageNum, pageSize, resourceType, vettingStatus, resourceName);
    }

    /**
     * 用户查询已通过审批的资源列表
     */
//    @PreAuthorize("@ss.hasPermi('platform:resource:listOwn')")
    @GetMapping("/listUser")
    @ApiOperation(value = "前台用户查询已通过审批的资源列表", notes = "前台用户查询已通过审批的资源列表")
    public AjaxResult listUser(Integer pageNum,Integer pageSize,Integer resourceType,Integer specialtyId,String resourceName, Integer sortord)
    {
        return platformUResourceService.selectPlatformUResourceListUser(pageNum, pageSize, resourceType, specialtyId, resourceName, sortord);
    }

    /**
     * 获取资源详细信息
     */
//    @PreAuthorize("@ss.hasPermi('platform:resource:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation(value = "获取资源详细信息",notes = "获取资源详细信息")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return platformUResourceService.selectPlatformUResourceById(id);
    }

    /**
     * 获取资源的前五个热搜
     */
    @GetMapping("/hotSearch")
    @ApiOperation(value = "获取资源的前五个热搜", notes = "获取资源的前五个热搜")
    public AjaxResult getHotSearch(){
        return platformUResourceService.selectHotSearch();
    }

    /**
     * 管理员审批资源是否通过
     */
    @Log(title = "【管理员审批资源是否通过】", businessType = BusinessType.UPDATE)
// @PreAuthorize("@ss.hasPermi('platform:resource:vetting')")
    @ApiOperation(value = "管理员审批资源是否通过", notes = "管理员审批资源是否通过")
    @PutMapping("/vetting")
    public AjaxResult vetting(@Valid @RequestBody VettingRequest vettingRequest) {
        if(vettingRequest.getVettingStatus() == 2 && null == vettingRequest.getNotPassingType()){
            return AjaxResult.error("请选择不通过的理由");
        }
        return platformUResourceService.updatePlatformUResourceVetting(vettingRequest);
    }

    /**
     * 增加下载量
     */
    @Log(title = "【增加下载量】", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "增加下载量", notes = "增加下载量")
    @PutMapping("/download")
    public void download(@RequestParam("resourceId") Long resourceId) {
        platformUResourceService.updatePlatformUResourceDownload(resourceId);
    }


    /**
     * 新增资源
     */
//    @PreAuthorize("@ss.hasPermi('platform:resource:add')")
    @Log(title = "【新增资源】", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增资源", notes = "新增资源")
    @PostMapping
    public AjaxResult add(@Valid @RequestBody PlatformUResourceVO platformUResourceVO)
    {
        if(platformUResourceVO.getResourceType() == 4){
            // if(StringUtils.isEmpty(platformUResource.getModelUrl())){
            //     return AjaxResult.error("请上传模型文件");
            // }
            // if(StringUtils.isEmpty(platformUResource.getChartletUrl())){
            //     return AjaxResult.error("请上传模型贴图");
            // }
            if(CollectionUtils.isEmpty(platformUResourceVO.getModelUrlArray())){
                return AjaxResult.error("请上传模型，贴图");
            }
            platformUResourceVO.setModelUrl(JSON.toJSONString(platformUResourceVO.getModelUrlArray()));
        }else {
            if(StringUtils.isEmpty(platformUResourceVO.getResourceUrl())){
                    return AjaxResult.error("请上传资源");
                }
        }
        return platformUResourceService.insertPlatformUResource(platformUResourceVO);
    }
    /**
     * 删除资源
     */
//    @PreAuthorize("@ss.hasPermi('platform:resource:remove')")
    @Log(title = "【删除资源】", businessType = BusinessType.DELETE)
    @ApiOperation(value = "删除资源", notes = "删除资源")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return platformUResourceService.deletePlatformUResourceByIds(ids);
    }

    @PostMapping("/downloadAndZip")
    @ApiOperation(value = "导出压缩文件", notes = "前端传来多个url以及文件地址")
    public void downloadAndZip(@RequestParam(value = "zipName", required = false) String zipName,
                               @RequestBody List<String> fileUrls,
                               HttpServletResponse response) {
        if (fileUrls == null || fileUrls.isEmpty()) {
            throw new RuntimeException("文件 URL 不能为空");
        }

        try {
            // 获取文件名，默认为 "模型.zip"
            String zipFileName = "model.zip";
            // if(StringUtils.isNotEmpty(zipName)){
            //     zipFileName = zipName + ".zip";
            // }
            zipFileName = URLEncoder.encode(zipFileName, StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20");

            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + zipFileName);

            try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) {
                byte[] buffer = new byte[4096];

                for (String fileUrl : fileUrls) {
                    try (InputStream inputStream = downloadFile(fileUrl)) {
                        String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
                        zos.putNextEntry(new ZipEntry(fileName));

                        int bytesRead;
                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            zos.write(buffer, 0, bytesRead);
                        }
                        zos.closeEntry();
                    } catch (IOException e) {
                        System.err.println("下载文件失败：" + fileUrl);
                    }
                }
                zos.flush();
            }
        } catch (IOException e) {
            throw new RuntimeException("文件压缩失败", e);
        }
    }

    private InputStream downloadFile(String fileUrl) throws IOException {
        int lastSlash = fileUrl.lastIndexOf("/");
        if (lastSlash != -1) {
            String path = fileUrl.substring(0, lastSlash + 1);
            String fileName = fileUrl.substring(lastSlash + 1);
            fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()).replace("+", "%20");
            fileUrl = path + fileName;
        }

        URL url = new URL(fileUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);

        int responseCode = connection.getResponseCode();
        if (responseCode != 200) {
            throw new IOException("文件下载失败，HTTP 响应码：" + responseCode);
        }

        return connection.getInputStream();
    }

}

